﻿using Newtonsoft.Json;
using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using SIMS.Common.Models;
using SIMS.Common.RestClient;
using SIMS.Shared.DTO;
using SIMS.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using SIMS.Shared.Models;

namespace SIMS.ViewModels
{
    public class LoginViewModel : BindableBase, IDialogAware
    {
        private IRegionManager _regionManager;
        private IContainerExtension _container;

        private readonly HttpRestClient _httpClient;

        public bool CanLogin
        {
            get
            {
                return !string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password);
            }
         }

        private bool isLoading;

        public bool IsLoading
        {
            get { return isLoading; }
            set { SetProperty(ref isLoading, value); }
        }

        private string userName;

        public string UserName
        {
            get 
            { 
                return userName; 
            }
            set 
            {
                SetProperty(ref userName, value);
                RaisePropertyChanged(nameof(CanLogin));
            }
        }

        private string password;

        public string Password
        {
            get 
            { 
                return password; 
            }
            set 
            { 
                SetProperty(ref password, value);
                RaisePropertyChanged(nameof(CanLogin));
            }
        }

        public LoginViewModel(IContainerExtension container,IRegionManager regionManager, HttpRestClient httpClient)
        {
            _container = container;
            _regionManager = regionManager;
            _httpClient = httpClient;
        }

        private DelegateCommand loadedCommand;

        public DelegateCommand LoadedCommand
        {
            get
            {
                if (loadedCommand == null)
                {
                    loadedCommand = new DelegateCommand(Loaded);
                }
                return loadedCommand;
            }
        }

        private void Loaded()
        {
            
        }

        private DelegateCommand loginCommand;

        public DelegateCommand LoginCommand
        {
            get
            {
                if (loginCommand == null)
                {
                    loginCommand = new DelegateCommand(Login);
                }
                return loginCommand;
            }
        }

        private async void Login()
        {
            if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)) {
                MessageBox.Show("请输入用户名和密码");
                return;
            }

            IsLoading = true;

            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Post;
            request.Parameters = new AccountInfo() { username = UserName, password = Password };
            request.Route = Api.LOGIN;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                long userId = (long)response.data;

                if (userId > 0)
                {
                    UserInfo.Instance.Id = (int)userId;
                    UserInfo.Instance.UserName = UserName;

                    var entity = await GetUser(userId);
                    if (entity != null)
                    {
                        UserInfo.Instance.NickName = entity.NickName;
                    }
                    IsLoading = false;
                    CloseWindow();
                }
                else
                {
                    IsLoading = false;
                    MessageBox.Show("用户名或密码错误");
                }
            }
            else
            {
                IsLoading = false;
                MessageBox.Show("登录失败，请重试");
            }
        }

        private async Task<UserDTO?> GetUser(long userId) 
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["id"] = userId;

            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Get;
            request.Parameters = parameters;
            request.Route = Api.USER_GETUSER;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1) 
            {
                var user = JsonConvert.DeserializeObject<UserDTO>(JsonConvert.SerializeObject(response.data));
                return user;
            }
            return null;
        }

        private DelegateCommand cancelCommand;

        public DelegateCommand CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new DelegateCommand(Cancel);
                }
                return cancelCommand;
            }
        }

        private void Cancel()
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel));
        }

        public string Title => "登录";

        public event Action<IDialogResult> RequestClose;

     
        public void CloseWindow() 
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
        }

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel));
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
         
        }
    }
}
